<?php
class Status extends AppModel{
	var $name = "Status";
	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id'
		),
		'Location' => array(
			'className' => 'Location',
			'foreignKey' => 'location_id',
			'dependent' => true
		)
	);
	
	var $order = "Status.id DESC";	//デフォではID降順
	
	function search($words, $category_id = 0, $offset = 0, $count = 10){
		$likes = array();
		foreach ($words as $key => $word) {
			$likes['or'][]['Status.text LIKE'] = "%{$word}%";
		}
		$options = array('conditions' => array($likes), 'limit' => $count, 'offset' => $offset);
		if($category_id != 0){
			$options['conditions']['and']['Status.category_id'] = $category_id;
		}
		return $this->find('all',$options);
	}
	
	function findByCampusId($campusId, $statusId = 0, $count = 10){
		$options = array(
				'conditions' => array(
					'User.campus_id' => $campusId,
					
				), 
				'limit' => $count
		);
		if($statusId != 0){
			$options['conditions']['Status.id <'] = $statusId;
		}
		return $this->find('all',$options);
	}
	
	function findAllByUserId($userId, $statusId = 0, $count = 10){
		$options = array(
				'conditions' => array(
					'User.id' => $userId
				),
				'limit' => $count
		);
		if($statusId != 0){
			$options['conditions']['Status.id <'] = $statusId;
		}
		return $this->find('all',$options);
	}
	
	function findNeighbor($lat, $lng, $scale = null){
		if($scale == null){
			$scale = 1;	//デフォルトのスケールは1
		}
		$northLat = floatval($lat) + 0.01 * $scale;
		$southLat = floatval($lat) - 0.01 * $scale;
		$eastLng = floatval($lng) + 0.01 * $scale;
		$westLng = floatval($lng) - 0.01 * $scale;
		$neighbors = $this->find('all',array('conditions' => array(
														'Location.lat between ? and ?' => array($southLat, $northLat), 
														'Location.lng between ? and ?' => array($westLng, $eastLng)
													)
												)
										);
		//pr($neighbors);
		return $neighbors;
	}
	
	function findNeighborInMap($north, $east, $south, $west){
		$neighbors = $this->find('all',array('conditions' => array(
													'Location.lat between ? and ?' => array($south, $north),
													'Location.lng between ? and ?' => array($west, $east)
												)						
											)
								);
		return $neighbors;
	}

	function getLatest($userId){
		return $this->find('first',array('conditions' => array('User.id' => $userId)));
	}
	function findMostNearest($lat, $lng, $exceptId){
		$data = $this->find('all',array('conditions' => array(
												'Status.created_at >' => date('Y-m-d H:i:s', strtotime('-1 day')),
												'User.twitter_user_id !=' => strval($exceptId)
										)
									)
		);
		$nearestIndex = 0;
		$shortestDistance = 100;
		//print_r($data);
		foreach($data as $k => $v){
			$tmpDistance = sqrt(pow(($lat - $v['Location']['lat']),2) + pow(($lng - $v['Location']['lng']),2));
			if($tmpDistance < $shortestDistance){
				$nearestIndex = $k;
			}
		}
		return $data[$nearestIndex];
	}

}
?>